package com.scy.edu;

import com.alibaba.druid.pool.DruidDataSource;
import com.scy.edu.entity.DataConfig;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ZooktaskApplication {

    public static DruidDataSource dataSource =null;

    public static void main(String[] args) {
        SpringApplication.run(ZooktaskApplication.class, args);

        DataConfig dataConfig = new DataConfig();
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        dataConfig.setDriverClass("com.mysql.jdbc.Driver");
        dataConfig.setUrl("jdbc:mysql://localhost:3306/lagou?useUnicode=true&characterEncoding=UTF-8&useSSL=false");
        dataConfig.setUserName("root");
        dataConfig.setPassword("admin");
        boolean boo = zkClient.exists("/dataSource");
        if(!boo){
            zkClient.createPersistent("/dataSource", dataConfig);
        }
        DataConfig config = zkClient.readData("/dataSource");
        dataSource = new DruidDataSource();
        dataSource.setUrl(config.getUrl());
        dataSource.setDriverClassName(config.getDriverClass());
        dataSource.setUsername(config.getUserName());
        dataSource.setPassword(config.getPassword());

        zkClient.subscribeDataChanges("/dataSource", new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                updateDataSource(o);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        });
    }

    private static void updateDataSource(Object obj){
        DataConfig config =(DataConfig)obj;
        dataSource = new DruidDataSource();
        dataSource.setUrl(config.getUrl());
        dataSource.setDriverClassName(config.getDriverClass());
        dataSource.setUsername(config.getUserName());
        dataSource.setPassword(config.getPassword());
    }
}
